package cn.stylefeng.guns.modular.recy.service;

import com.baomidou.mybatisplus.extension.service.impl.*;
import cn.stylefeng.guns.modular.recy.mapper.*;
import cn.stylefeng.guns.modular.recy.entity.*;
import org.springframework.stereotype.*;
import org.springframework.beans.factory.annotation.*;
import com.baomidou.mybatisplus.core.conditions.query.*;
import com.baomidou.mybatisplus.core.conditions.*;
import java.util.*;
import cn.stylefeng.guns.modular.recy.utils.*;
import me.chanjar.weixin.mp.bean.message.*;
import org.apache.commons.lang3.*;
import cn.stylefeng.guns.modular.weixin.utils.*;
import java.lang.invoke.*;

@Service
public class WechatUserService extends ServiceImpl<WechatUserMapper, WechatUser>
{
    @Autowired
    private UserNoCreator userNoCreator;
    
    public WechatUser getByOpenId(final String openid) {
        final QueryWrapper<WechatUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(WechatUser::getOpenId, openid);
        WechatUser wechatUser = (WechatUser)this.getOne(queryWrapper, false);
        if (wechatUser == null) {
            wechatUser = WechatUser.builder().openId(openid).createTime(new Date()).status(DictUtils.me().id("wxuser_status::common")).build();
            wechatUser.setUserNo(this.userNoCreator.incrementAndGet());
            wechatUser.insert();
        }
        return wechatUser;
    }
    
    public WechatUser getByOpenId(final WechatUser user) {
        final QueryWrapper<WechatUser> queryWrapper = (QueryWrapper<WechatUser>)new QueryWrapper();
        final String openid = user.getOpenId();
        queryWrapper.lambda().eq(WechatUser::getOpenId, openid);
        WechatUser wechatUser = (WechatUser)this.getOne((Wrapper)queryWrapper, false);
        if (wechatUser == null) {
            wechatUser = WechatUser.builder().openId(openid).createTime(new Date()).status(DictUtils.me().id("wxuser_status::common")).userNo(Long.valueOf(this.userNoCreator.incrementAndGet())).wechatNickName(user.getWechatNickName()).avatarUrl(user.getAvatarUrl()).phone(user.getPhone()).userId(user.getUserId()).mpCode(user.getMpCode()).build();
            wechatUser.insert();
        }
        return wechatUser;
    }
    
    public WechatUser getByOpenId(final WxMpXmlMessage wxMessage) {
        final WechatUser user = this.getByOpenId(wxMessage.getFromUser());
        if (StringUtils.isBlank((CharSequence)user.getMpCode())) {
            final String appNameByMpNo = WxUtils.getMpCode(wxMessage.getToUser());
            user.setMpCode(appNameByMpNo);
            user.updateById();
        }
        return user;
    }
    
    public WechatUser findByOpenId(final String openId) {
        final QueryWrapper<WechatUser> wechatUserQueryWrapper = (QueryWrapper<WechatUser>)new QueryWrapper();
        wechatUserQueryWrapper.lambda().eq(WechatUser::getOpenId, openId);
        return (WechatUser)this.getOne((Wrapper)wechatUserQueryWrapper, false);
    }
}
